<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <title></title>
  <link href="css/semantic.min.css" type="text/css" rel="stylesheet">
</head>

<script id="table" type="text/x-handlebars-template">
  <table class="ui celled table">
    <thead>
      <tr>
        <th>id</th>
        <th>Code</th>
        <th>状态</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody>
      {{#each codeList}}
      <tr class="{{#if status}}positive{{else}}negative{{/if}}">
        <td>{{id}}</td>
        <td>{{code}}</td>
        <td>{{#if status}}正常{{else}}已使用{{/if}}</td>
        <td><button class="ui button" onclick="useCode('{{code}}')">测试</button></td>
      </tr>
      {{/each}}
    </tbody>
  </table>
</script>

<body>
  <div class="ui menu">
    <div class="header item"><i class="left delicious icon"></i>兑换码</div>
  </div>
  <div class="ui grid">
    <div class="two wide column"></div>
    <div class="twelve wide column" id="table-container">

    </div>
    <div class="two wide column">
      <button class="ui button" id="refresh">刷新</button>
    </div>
  </div>
  <script src="zepto.min.js"></script>
  <script src="handlebars.js"></script>
<script>
  var source = $("#table").html();
  var template = Handlebars.compile(source);
  var refreshTable = function(){
    $.get('/api/code/list/all', function(data){
      $("#table-container").html((template({codeList:data})))
    })
  };
  var useCode = function(id){
    $.ajax({
      type: 'GET',
      url: 'http://localhost:8008/api/code/' + id,
      dataType: 'jsonp',
      success: function(data){
        console.log(data);
        refreshTable()
      },
      error: function(xhr, type){
        alert('Ajax error!')
      }
    })
  };

  refreshTable();
  $("#refresh").click(function() {
    refreshTable()
  });
</script>
</body>
</html>